﻿(function(jQuery) {
    jQuery.fn.multipleSelect = function(o) {
        return this.each(function() {
            new jQuery.multipleSelect(this, o);
        });
    };

    jQuery.multipleSelect = function(e, o) {
        if (!jQuery.multipleSelect.bodyClickBound) {
            $('body').click(function() { if (!jQuery.multipleSelect.active) $('.multipleselectpopup').hide(); });
            jQuery.multipleSelect.bodyClickBound = true;
        }

        this.options = o || {};
        this.name = e.name;
        this.select = jQuery(e);
        this.autoCompleteUrl = this.select.attr('acurl');
        this.selectUrl = this.select.attr('selurl');
        this.holder = this.select.parent();
        this.maxitems = this.options.maxitems ? this.options.maxitems : 12;
        this.maxwidth = this.options.maxwidth ? this.options.maxwidth : 'auto';
        this.filteritems = this.options.filteritems ? this.options.filteritems : 10;
        this.select.hide();
        this.tree = this.select.hasClass('multitree');
        this.treeIndenter = String.fromCharCode(8212);

        var div = this.select.parent();
        var self = this;
        if (this.options.init) self.init(true);

        $('a:first', div).click(function() { self.init(); return false; });

        if (!jQuery.multipleSelects) jQuery.multipleSelects = new Array();
        jQuery.multipleSelects[this.name] = this;
        return self;
    };

    jQuery.multipleSelect.initByClassName = function(className, o) {
        if ($(className).length > 0) $(className).multipleSelect(o);
    };

    jQuery.multipleSelect.fn = jQuery.multipleSelect.prototype = {
        multipleSelect: '1.0.0'
    };

    jQuery.multipleSelect.fn.extend = jQuery.multipleSelect.extend = jQuery.extend;

    jQuery.multipleSelect.fn.extend({

        init: function(skip) {
            var self = this;
            var sel = self.select;

            if (sel.hasClass('processed')) {
                self.toggle();
                return self;
            }

            var disabled = sel.is(':disabled');
            var name = sel.attr('name');
            var div = sel.parent();
            if ($('a:first', div).length == 0) div.append('<div class="checklisttitle"><a href="#">Выбрать</a></div>');
            div.append('<div class="popupwrapper multipleselectpopup"><div class="msitems popup"></div></div>');
            self.popup = $('div.popupwrapper', div);
            self.popup.bind('mouseover', function() { jQuery.multipleSelect.active = true; }).bind('mouseout', function() { jQuery.multipleSelect.active = false; });
            self.itemscontainer = $('div.msitems', div);

            self.link = $('a:first', div);

            if (self.autoCompleteUrl) {
                self.itemscontainer.append('<nobr><input class="autocomplete" />&nbsp;');
                self.itemscontainer.append('<a href="#" onclick="return selectFilterUsers(\'' + self.selectUrl + '\',\'' + self.name + '\')"><img src="img/buttons/browsedialog.gif" class="middle"/></a></nobr>');
                self.ac = $('input.autocomplete', this.itemscontainer);
                self.ac.autocomplete(base + self.autoCompleteUrl).bind('result', function(e, d) { self.acResult(e, d); });
            }

            var cbhtml = '<ul class="checklist">';
            var tree_regex = /(\s\/\s)/g;
            $('option', sel).each(function(i, el) {
                var val = el.value;
                var txt = el.text;
                var cbid = name + '_' + val;
                var listyle = '';

                if (self.tree) {
                    var m = txt.match(tree_regex);
                    if (m) {
                        var cc = el.text.split(tree_regex);
                        var level = (cc.length - 1) / 2;
                        txt = cc[cc.length - 1];
                        el.text = txt;
                        for (var i = 0; i < level; i++) el.text = self.treeIndenter + el.text;
                        listyle = 'style="margin-left:' + level * 18 + 'px"';
                    }
                }
                cbhtml += '<li ' + listyle + '><label for="' + cbid + '" class="radio"><input type="checkbox" value="' + val + '" id="' + cbid + '" ' + (el.selected ? ' checked="true"' : '') + '/>' + txt + '</label></li>'
            });
            cbhtml += '</ul>';
            cbhtml += '<a href="#" class="mshidelink"><img src="img/close.gif" /></a>';
            self.itemscontainer.append(cbhtml);
            $('a.mshidelink', self.itemscontainer).click(function() { self.popup.hide(); return false; });
            self.list = $('ul.checklist', self.itemscontainer);
            $('input[type="checkbox"]', self.list).bind('click', function() { self.itemClicked(this) });
            self.optionsToString();

            self.setHeight();
            sel.addClass('processed').hide();

            if (!skip) self.toggle();
            jQuery.data(self.select.get(0), 'multipleselect', self);
            return self;
        },

        setHeight: function() {
            var self = this;
            var itemcount = $('option', self.select).length;
            if (itemcount > self.maxitems) itemcount = self.maxitems;
            var height = itemcount * 20 + 2;
            self.list.css('height', height);
        },

        toggle: function() {
            var self = this;
            var div = self.popup;
            var hide = div.is(':visible');
            var left = self.link.position().left;
            self.popup.css('position', 'absolute').css('left', left);
            self.popup.bgiframe();
            $('div.multipleselectpopup').hide();
            if (!hide) div.show();
        },

        addOption: function(id, name, selected) {
            var self = this;
            var cbid = self.select.attr('name') + '_' + id;
            self.list.append('<li><label for="' + cbid + '" class="radio"><input type="checkbox" value="' + id + '" id="' + cbid + '" ' + (selected ? ' checked="true"' : '') + '/>' + name + '</label></li>');
            $('#' + cbid, self.list).bind('click', function() { self.itemClicked(this) });
            self.setHeight();
        },

        optionsToString: function() {
            var self = this;
            var sel = self.select;
            var text = '';
            var trim_tree_re = new RegExp('^([' + self.treeIndenter + '])*');
            if ($('option:selected', sel).length > 0)
                $('option:selected', sel).each(function(i, el) { var el_text = self.tree? el.text.replace(trim_tree_re,'') : el.text; text += ((i > 0) ? ', ' : '') + el_text; });
            else
                text = 'Выбрать';
            self.link.attr('title', text).html(text);
        },

        filterItems: function(str) {
            var self = this;
            if (str.length == 0) {
                $('li', self.list).show();
            }
            else {
                $('li', self.list).hide();
                $("li label", self.list).each(function(i, el) { el = $(el); if (el.text().toLowerCase().indexOf(str) >= 0) el.parent().show(); });
            }
        },

        acResult: function(e, d) {
            var self = this;
            var name = d[0];
            var id = d[1];

            $(e.target).val('');
            if ($('option[value="' + id + '"]', self.select).length > 0) return;
            self.select.append('<option selected value="' + id + '">' + name + '</option>');
            self.addOption(id, name, true);
            self.optionsToString();
            self.select.trigger('change');
        },

        itemClicked: function(cb) {
            var self = this;
            var sel = this.select;

            $('option[value="' + cb.value + '"]', sel).attr('selected', cb.checked);
            sel.trigger('change');
            if (self.options.onchange) self.options.onchange(self);
            self.optionsToString();
        },

        unwrapControl: function(o) {
            var self = this;
            self.select.show();
            $('div', self.holder).hide();
        },

        wrapControl: function(skip) {
            var self = this;
            self.select.hide();
            $('div', self.holder).show();
            if (skip) self.popup.hide();
        }
    });

})(jQuery);

$(function() {
    jQuery.multipleSelect.initByClassName('.multipleselect');
});
